package cn.net.dpi.wlqc.server.kafka;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaProducerConfig {

    @Value("${spring.kafka.bootstrap-servers:}")
    private String kafkaServer;
    @Value("${spring.kafka.producer.linger-ms:0}")
    private Integer lingerMs;
    @Value("${spring.kafka.producer.max-request-size:1048576}")
    private Integer maxRequestSize;
    /**
     * 批量发送大小(16k)
     */
    @Value("${spring.kafka.producer.batch-size:16384}")
    private Integer batchSize;
    /**
     * 缓冲区大小（32MB）
     */
    @Value("${spring.kafka.producer.buffer-memory:33554432}")
    private Long bufferMemory;

    @Bean
    public ProducerFactory<String, Object> producerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer);//kafka 地址
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);//序列化
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);//序列化
        props.put(ProducerConfig.ACKS_CONFIG, "all");//确认机制，all是所有副本确认，1是一个副本确认，0是不需要副本确认
        props.put(ProducerConfig.LINGER_MS_CONFIG, lingerMs);//批量发送等待时间  和上面的batch-size谁先到先发送
        props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, maxRequestSize);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);//批量发送大小(16k)
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);// 缓冲区大小（32MB）
        return new DefaultKafkaProducerFactory<>(props);
    }

    /**
     * @return org.springframework.kafka.core.KafkaTemplate<java.lang.String, java.lang.Object>
     * @Title kafkaTemplate
     * @Description kafka生产者工具类
     */
    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}
